package net.mengkang;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;

import java.io.File;

public class MkTomcat {

    public static void main(String[] args) throws LifecycleException {

        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8080);

        Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());

        Tomcat.addServlet(ctx, "MkServlet", new DispatcherServlet("net.mengkang.controller"));

        ctx.addServletMappingDecoded("/*", "MkServlet");

        setFilter(ctx);

        tomcat.start();
        tomcat.getServer().await();
    }

    private static void setFilter(Context ctx) {
        FilterDef traceFilter = new FilterDef();
        traceFilter.setFilterName("traceFilter");
        traceFilter.setFilterClass(TraceFilter.class.getName());

        FilterMap failedRequestFilterMap = new FilterMap();
        failedRequestFilterMap.setFilterName("traceFilter");
        failedRequestFilterMap.addURLPattern("/*");

        ctx.addFilterDef(traceFilter);
        ctx.addFilterMap(failedRequestFilterMap);
    }
}
